package com.hschinese.pronunciation.widget;

import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.ScaleAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hschinese.pronunciation.R;
import com.hschinese.pronunciation.bean.PlayAssetData;
import com.hschinese.pronunciation.bean.WordBean;
import com.hschinese.pronunciation.interfaces.LessonProgressInterface;
import com.hschinese.pronunciation.interfaces.NextLessonInterface;
import com.hschinese.pronunciation.interfaces.PlayClickListener;
import com.hschinese.pronunciation.interfaces.PlayCompleteListener;
import com.hschinese.pronunciation.utils.HsSoundUtil;
import com.hschinese.pronunciation.utils.Logger;
import com.hschinese.pronunciation.utils.SimpleRecordUtil;

import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import butterknife.ButterKnife;
import studychinese.view.ComplexWordHandWritingView;

/**
 * Created by buba on 2018/2/5.
 */

public class ComplexWordView extends LinearLayout implements PlayCompleteListener, View.OnClickListener {
    @Bind(R.id.btn_check)
    Button btnCheck;
    @Bind(R.id.iv_mean)
    ImageView ivMean;
    @Bind(R.id.tv_mean)
    TextView tvMean;
    @Bind(R.id.btn_bak)
    Button btnBak;
    @Bind(R.id.rl_back)
    RelativeLayout rlBack;
    @Bind(R.id.play_control_org_bar)
    RoundProgressBar mPlayOrgBar;
    @Bind(R.id.play_control_standard)
    ImageView mPlayStandard;
    private Context context;
    @Bind(R.id.bsv_view)
    ComplexWordHandWritingView bsvView;
    @Bind(R.id.rl_view)
    RelativeLayout rlView;
    @Bind(R.id.iv_name)
    TextView ivName;
    @Bind(R.id.rl_contstrction_parient)
    RelativeLayout rl_contstrction_parient;
    @Bind(R.id.iv_good_hand)
    ImageView ivGoodHand;
    @Bind(R.id.iv_good_star)
    ImageView ivGoodStar;
    @Bind(R.id.rl_good)
    RelativeLayout rlGood;
    @Bind(R.id.rl_forward)
    RelativeLayout rlForward;
    private LessonProgressInterface mListener = null;
    private String name;
    private NextLessonInterface mNextListener = null;
    private int currentPosition;
    private Animation.AnimationListener wordViewAnimListener = null;
    private Animation chooseViewAnimation = null;
    // 每个空间都添加一种动画
    long durationMillis = 1000, delayMillis = 0;

    public ComplexWordView(Context context) {
        super(context);
        this.context = context;
        initViews(context);
    }

    public ComplexWordView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        initViews(context);
    }

    private void initViews(Context context) {
        View inflate = LayoutInflater.from(context).inflate(R.layout.complex_word_view, null);
        ButterKnife.bind(this, inflate);
        btnCheck.setOnClickListener(this);
        btnBak.setOnClickListener(this);
        mPlayStandard.setOnClickListener(this);
        this.addView(inflate);
    }

    public void setData(int position) {
        currentPosition = position;
        rlGood.setVisibility(GONE);
//        ivName.setImageResource(imgRes[position]);
        name = "bishun_" + position;
        try {
            WordBean wordBean = bsvView.setText(name);
            if (wordBean != null) {
                // TODO: 2018/2/7 设置数据 图片 释义 音频
                mStandardUrl = wordBean.getData().get(0).getBihua_mingcheng();
            }
            bsvView.setDrawListener(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (mListener != null) {
            mListener.setProgress(51, position);
        }
        if (currentPosition != 0) {
            addAnimation();
        }
    }

    public void setListener(LessonProgressInterface listener) {
        mListener = listener;
    }

    public void setNextListener(NextLessonInterface listener) {
        mNextListener = listener;
    }

    private void addAnimation() {
        if (rl_contstrction_parient != null) {
            wordViewAnimListener = new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {
                }

                @Override
                public void onAnimationEnd(Animation animation) {


                }

                @Override
                public void onAnimationRepeat(Animation animation) {
                }
            };
            chooseViewAnimation = scaleIn(rl_contstrction_parient, durationMillis, delayMillis, wordViewAnimListener);
            rl_contstrction_parient.post(new Runnable() {
                @Override
                public void run() {
                    chooseViewAnimation.start();
                }
            });

        }
    }

    private Animation scaleIn(View view, long durationMillis, long delayMillis, Animation.AnimationListener l) {
        ScaleAnimation animation = new ScaleAnimation(0, 1, 0, 1, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        animation.setDuration(durationMillis);
        animation.setStartOffset(delayMillis);
        view.setVisibility(View.VISIBLE);
        view.startAnimation(animation);
        animation.setAnimationListener(l);
//        animation.cancel();
        return animation;
    }

    private Animation scaleBigIn(View view, long durationMillis, long delayMillis, Animation.AnimationListener l) {
        ScaleAnimation animation = new ScaleAnimation(0, 2, 0, 2, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        animation.setDuration(durationMillis);
        animation.setStartOffset(delayMillis);
        view.setVisibility(View.VISIBLE);
        view.startAnimation(animation);
        animation.setAnimationListener(l);
        animation.cancel();
        return animation;
    }

    public void beforeWord() {
        if (currentPosition <= 0)
            return;
        currentPosition--;
        rlBack.setVisibility(GONE);
        rlForward.setVisibility(VISIBLE);
        if (currentPosition < 51) {
            setData(currentPosition);
        } /*else {
            // TODO 进入下一课. 会掉到StudyActivity页面来进行View的切换
            // mNextListener.onLessonChanged(lessonType - 1);
            weithLess--;
            currentPosition=0;
            initData();
        }*/
    }

    /* private void updateViewData() {
         if (currentPosition < 0) return;
         if (mListener != null) {
             mListener.setProgress(imgRes.length, currentPosition);
         }
     }*/
    public void nextWord() {
        // TODO 数据切换，涉及到界面上文字和图片的切换

        currentPosition++;
        rlBack.setVisibility(GONE);
        rlForward.setVisibility(VISIBLE);
        if (currentPosition < 51) {
            setData(currentPosition);
        } /*else {
           weithLess++;
           currentPosition=0;
           initData();
           //  Utils.showDialog(mContext, R.string.next_lesson_dialog_msg, lessonType, mNextListener);
       }*/
    }

    /**
     * 用户画完，此时应该有点赞动画出现
     */
    @Override
    public void playComplete() {
        Animation animation1 = AnimationUtils.loadAnimation(context, R.anim.translate_good_star_in);
        ivGoodStar.setAnimation(animation1);
        rlGood.postDelayed(new Runnable() {
            @Override
            public void run() {
                rlGood.setVisibility(VISIBLE);
            }
        },500);
        scaleIn(ivGoodHand, 300, 500, new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                rlGood.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        rlGood.setVisibility(GONE);
                    }
                }, 1000);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
    }
    private PlayClickListener mPlayClickListener;

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_bak:
                // TODO: 2018/2/7 反转回来
                float centerX = rl_contstrction_parient.getWidth() / 2f;
                float centerY = rl_contstrction_parient.getHeight() / 2f;
                // 构建3D旋转动画对象，旋转角度为360到270度，这使得ImageView将会从可见变为不可见，并且旋转的方向是相反的
                final Rotate3dAnimation rotation = new Rotate3dAnimation(360, 270, centerX, centerY, 310.0f, true);
                // 动画持续时间500毫秒
                rotation.setDuration(200);
                // 动画完成后保持完成的状态
                rotation.setFillAfter(true);
                rotation.setInterpolator(new AccelerateInterpolator());
                // 设置动画的监听器
                rotation.setAnimationListener(new TurnToView2());
                rl_contstrction_parient.startAnimation(rotation);
                break;
            case R.id.btn_check:
                // TODO: 2018/2/7 反转过去查看释义图
                // 获取布局的中心点位置，作为旋转的中心点
                float centerX1 = rl_contstrction_parient.getWidth() / 2f;
                float centerY1 = rl_contstrction_parient.getHeight() / 2f;
                // 构建3D旋转动画对象，旋转角度为0到90度，这使得ListView将会从可见变为不可见
                final Rotate3dAnimation rotation1 = new Rotate3dAnimation(0, 90, centerX1, centerY1, 310.0f, true);
                // 动画持续时间500毫秒
                rotation1.setDuration(200);
                // 动画完成后保持完成的状态
                rotation1.setFillAfter(true);
                rotation1.setInterpolator(new AccelerateInterpolator());
                // 设置动画的监听器
                rotation1.setAnimationListener(new TurnToView1());
                rl_contstrction_parient.startAnimation(rotation1);
                break;
            case R.id.play_control_standard:
                // TODO: 2018/2/7 播放音频
                playStandard();
                if (mPlayClickListener != null) {
                    mPlayClickListener.onPlayClicked(isPlaying);
                }
                break;
        }
    }
    private boolean isPlaying = false;
    private String mStandardUrl = null;
    private PlayAssetData mPrePlayData = null;
    public void playStandard() {
        if (mStandardUrl != null && !TextUtils.isEmpty(mStandardUrl)) {
            if (mPrePlayData != null) {
                mPrePlayData.stopPlay();
            }
            mPrePlayData = HsSoundUtil.playAsset(context, mStandardUrl);
//            Logger.e("xionghy - duration: " + mPrePlayData.getDuration());
            mPlayOrgFlag = false;
            play();
        } else {
            Logger.e("Org data was not exist!");
        }
    }
    private void play() {
        mPlayStandard.setImageResource(R.drawable.voice_animator);
        AnimationDrawable draw = (AnimationDrawable) mPlayStandard.getDrawable();
        draw.setOneShot(true);
        draw.start();
        startTask(1.5f, draw);
        updateProgress(1200);
    }
    private void startTask(float t, final AnimationDrawable draw) {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                draw.stop();
            }
        }, (int) (t * 1000));
    }

    public void destory() {
        SimpleRecordUtil.getInstance(context).stopPlayer();
    }
    class TurnToView1 implements Animation.AnimationListener {

        @Override
        public void onAnimationStart(Animation animation) {
        }

        @Override
        public void onAnimationEnd(Animation animation) {
            // 获取布局的中心点位置，作为旋转的中心点
            float centerX = rl_contstrction_parient.getWidth() / 2f;
            float centerY = rl_contstrction_parient.getHeight() / 2f;
           /* mView1.setVisibility(View.GONE);
            // 将ImageView显示
            mView2.setVisibility(View.VISIBLE);
            mView2.requestFocus();*/
            rlForward.setVisibility(GONE);
            rlBack.setVisibility(VISIBLE);
            // 构建3D旋转动画对象，旋转角度为270到360度，这使得ImageView将会从不可见变为可见
            final Rotate3dAnimation rotation = new Rotate3dAnimation(270, 360, centerX, centerY,
                    310.0f, false);
            // 动画持续时间500毫秒
            rotation.setDuration(200);
            // 动画完成后保持完成的状态
            rotation.setFillAfter(true);
            rotation.setInterpolator(new AccelerateInterpolator());
            rl_contstrction_parient.startAnimation(rotation);
        }

        @Override
        public void onAnimationRepeat(Animation animation) {
        }
    }

    /**
     * 注册在ImageView点击动画中的动画监听器，用于完成ImageView的后续动画。
     */
    class TurnToView2 implements Animation.AnimationListener {
        @Override
        public void onAnimationStart(Animation animation) {
        }

        /**
         * 当ImageView的动画完成后，还需要再启动ListView的动画，让ListView从不可见变为可见
         */
        @Override
        public void onAnimationEnd(Animation animation) {
            // 获取布局的中心点位置，作为旋转的中心点
            float centerX = rl_contstrction_parient.getWidth() / 2f;
            float centerY = rl_contstrction_parient.getHeight() / 2f;
            rlBack.setVisibility(View.GONE);
            rlForward.setVisibility(View.VISIBLE);
            // 构建3D旋转动画对象，旋转角度为90到0度，这使得ListView将会从不可见变为可见，从而回到原点
            final Rotate3dAnimation rotation = new Rotate3dAnimation(90, 0, centerX, centerY,
                    310.0f, false);
            // 动画持续时间500毫秒
            rotation.setDuration(200);
            // 动画完成后保持完成的状态
            rotation.setFillAfter(true);
            rotation.setInterpolator(new AccelerateInterpolator());
            rl_contstrction_parient.startAnimation(rotation);
        }

        @Override
        public void onAnimationRepeat(Animation animation) {
        }

    }
    private boolean mPlayOrgFlag = false;
    public void resetProgressBar() {
        if (mPlayOrgBar != null) {
            mPlayOrgFlag = true;
        }
    }
    int progress = 0;
    private void updateProgress(int time) {
        progress = 0;
        mPlayOrgBar.setProgress(progress);
        new Thread(new Runnable() {

            @Override
            public void run() {
                while(progress <= 100){
                    if (mPlayOrgFlag) break;
                    progress += 5;
                    mPlayOrgBar.setProgress(progress);
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                mPlayOrgFlag = false;
                progress = 0;
                mPlayOrgBar.setProgress(progress);
            }
        }).start();
    }
}
